//
//  UserManager.m
//  Ranging_dev
//
//  Created by Mr.Dynasty on 2019/4/1.
//  Copyright © 2019 Mr.Dynasty. All rights reserved.
//

#import "UserManager.h"

static UserManager *infoManager;

@interface UserManager ()

@property (strong, nonatomic) NSUserDefaults *userDef;

@end
@implementation UserManager

+ (instancetype)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        infoManager = [[UserManager alloc] init];
        [infoManager initUserInfoModel];
    });
    return infoManager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _userDef = [NSUserDefaults standardUserDefaults];
    }
    return self;
}

- (void)initUserInfoModel {
    if (!self.userInfoModel) {
        self.userInfoModel = [[UserInfoModel alloc] init];
        [self saveUserInfoModel:self.userInfoModel];
    }
    
}

- (void)saveUserInfoModel:(UserInfoModel *)userInfoModel {
    NSData *userInfoData = [userInfoModel yy_modelToJSONData];
    [self saveObject:userInfoData forKey:UserInfo];
}

- (BOOL)saveObject:(NSObject *)object forKey:(NSString *)key {
    @try {
        if ([object isKindOfClass:[UserInfoModel class]]) {
            UserInfoModel *model = (UserInfoModel *)object;
            NSMutableDictionary *dict = [model convert2Dictionary];
            [_userDef setValue:dict.copy forKey:key];
        }else{
            [_userDef setValue:object forKey:key];
        }
        return [_userDef synchronize];
    }
    @catch (NSException *exception) {
        return NO;
    }
}

/**
 get 方法，返回用户数据
 
 @return 用户数据类
 */
- (UserInfoModel *)userInfoModel {
    NSData *infoJson = [_userDef objectForKey:UserInfo];
    UserInfoModel *userInfoModel =  [UserInfoModel yy_modelWithJSON:infoJson];
    return userInfoModel;
}


@end
